package reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import reggie.common.customException;
import reggie.dto.SetmealDto;
import reggie.entity.Setmeal;
import reggie.entity.SetmealDish;
import reggie.service.SetmealDishService;
import reggie.service.SetmealService;
import reggie.mapper.SetmealMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【setmeal(套餐)】的数据库操作Service实现
 * @createDate 2022-08-12 19:56:16
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>
        implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    //新增套餐
    @Transactional //事务注解 防止第一次操作事务 第二次操作执行不了 破坏了 原子性和一致性
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息 操作setmeal 执行添加操作
        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map(item -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        //保存套餐和菜品的关联信息 操作setmeal_dish 执行添加操作
        setmealDishService.saveBatch(setmealDishes);

    }

    /**
     * 删除套餐
     *
     * @param ids
     */
    @Override
    @Transactional(noRollbackFor = customException.class)
    public void removeWithDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getStatus, 0)
                .in(Setmeal::getId,ids);
        //删除套餐表中的数据
        int num = baseMapper.delete(queryWrapper);
        if(num == 0){
            throw new customException("在售套餐无法删除");
        }else if (num!=ids.size()){
            throw new customException("停售套餐删除成功,在售套餐暂时无法删除");
        }
        //this.remove(queryWrapper);
    }

    @Override
    public SetmealDto getSetmealById(Long id) {
        return baseMapper.selectSetmealById(id);
    }
}




